<?php

namespace app\api\controller;

use app\api\model\mysql\MallAccountLog;
use app\api\model\mysql\MallCart;
use app\api\model\mysql\MallGoods;
use app\api\model\mysql\MallGoodsSku;
use app\api\model\mysql\MallOrder;
use app\api\model\mysql\MallOrderGoods;
use app\api\model\mysql\MallOrderRefund;
use app\api\model\mysql\MallSetting;
use app\api\model\mysql\MallUser;
use app\api\model\mysql\MallUserAddress;
use app\api\model\mysql\MallUserPaylog;
use app\common\lib\ArrClass;
use app\common\lib\Str;
use app\common\model\MallCommissionLevel;
use think\facade\Log;
use app\common\lib\Show;
use app\common\lib\Status;
use think\Model;

class Order extends Base
{
    /**
     * 购物车列表
     * @return \think\response\Json
     */
    public function getCart(){
        $openid =$this->request->param('openid','','trim');

        try{
            $list= (new MallCart())->alias('c')
                ->field('c.id,c.goods_name,c.image,c.goods_price,c.total,s.stock,c.option_name as get_specs_value_ids')
                ->join('mall_goods_sku s','s.id=c.option_id')
                ->join('mall_goods g','c.goods_id = g.id')
                ->where("c.openid",$openid)
                ->where('g.delete_time',NULL)
                ->select()
                ->toArray();
        }catch (\Exception $e){
            Log::error("goods_detail" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, '查询失败');
        }

        return Show::json_show(Status::mini_normal, "ok", [
            'cartlist' =>$list ?? [],

        ]);
    }

    /**
     * 更新购物车商品数量
     * @return \think\response\Json
     */
    public function changeCarGoodsNum()
    {
        $cart_id = $this->request->param('cart_id', '0', 'intval');
        $openid = $this->request->param('openid', '0', 'trim');
        $goodsnum = $this->request->param('goodsnum', '1', 'intval');
        $data = array('total' => $goodsnum);
        $where = [['id', '=', $cart_id]];
        // 判断库存
        $goodsinfo=array();
        try{
            $cartinfo =(new MallCart())->getGoodsInfoByCartId($openid,$cart_id);
            if($cartinfo){
                $goodsinfo =(new MallGoodsSku())->getGoodsSkuById($cartinfo['goods_id'],$cartinfo['option_id']);
            }
        }catch (\Exception $e){
            Log::error("changecartnum" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, '查询失败');
        }
        if(empty($goodsinfo)){
            return Show::json_show(Status::mini_error, '商品已下架');
        }
        if($goodsinfo['stock'] ==0 || $goodsinfo['stock']<$goodsnum){
            return Show::json_show(Status::mini_error, '商品库存不足，请稍后再试');
        }
        try {
            (new MallCart())->where($where)->save($data);
        } catch (\Exception $e) {
            Log::error("changecartnum" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, '查询失败');
        }
        return Show::json_show(Status::mini_normal, "ok", [

        ]);
    }

    /**
     * 删除购物车
     * @return \think\response\Json
     */
    public function deleteByCart(){
        $cart_ids = $this->request->param('cart_ids', '', 'trim');
        try {
            (new MallCart())->deleteByCartId($cart_ids);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '删除失败');
        }
        return Show::json_show(Status::mini_normal, "删除成功", [
        ]);
    }


    /**
     * 购物车选购下单
     * @return \think\response\Json
     */
    public function cartToBuy(){
        $openid =$this->request->param('openid','','trim');
        $cart_ids =$this->request->param('cart_ids','','trim');
        if (!$cart_ids) {
            return Show::json_show(Status::mini_error, '请选择购买商品');
        }

        try{
            $goods=(new MallCart())->getCartListByIds($cart_ids);
            $address= (new MallUserAddress())->getUserAddressByDefault($openid);
            $member =(new MallUser())->getUserByList($openid,'id,nickName,balance,commission_level');
        }catch (\Exception $e){
            Log::error("goods_detail" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, '查询失败');
        }

        // 商品总额
        $goodsprice =0;
        foreach ($goods as $k=>$v){
            $goodsprice+= round($v['price']*$v['total'],2);
        }
        $totalgoodsprice =$goodsprice;
        //dump($goodsprice);exit();
        $shippingfee =0;  //运费
        // 分销商等级
        try{
            $levelinfo = (new MallCommissionLevel())->getlevelInfo($member['commission_level']);
        }catch (\Exception $e) {
            Log::error("level" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        $zhekou =0;
        if($levelinfo){
            $zhekou =$levelinfo['sharepersont'];
            if($zhekou <= 0){
                $goodsprice = round($goodsprice, 2);
            }else {
                $goodsprice = round($goodsprice * $zhekou / 10, 2);
            }
        }
        // 合计
        $payprice =round($goodsprice+$shippingfee,2);
        $order=array(
            'goodsprice'=>number_format($totalgoodsprice,2),
            'shippingfee'=>number_format($shippingfee,2),
            'zhekou'=>$zhekou,
            'levelname' =>$levelinfo['levelname'],
            'balance'=>number_format($member['balance'],2),
            'payprice'=>number_format($payprice,2)
        );

        return Show::json_show(Status::mini_normal, "ok", [
            'address' =>$address ?? [],
            'goods' =>$goods,
            'order' =>$order,
        ]);

    }


    /**
     * 立即购买
     * @return \think\response\Json
     */
    public function directOrdertoBuy(){

        $openid =$this->request->param('openid','','trim');
        $goods_id =$this->request->param('goods_id',0,'intval');
        $option_id =$this->request->param('option_id',0,'intval');
        $buynum =$this->request->param('buynum',0,'intval');
        try {
            $goods = (new MallGoods())->getGoodsDetail($goods_id, 'id,cate_id,cate_ids,title,describe,images,video,price,sales,thumb_title,sku_id,logo,stock,status');
            $member =(new MallUser())->getUserByList($openid,'id,nickName,commission_level');
        } catch (\Exception $e) {
            Log::error("goods_detail" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, "查询错误");
        }

        if (!$goods) {
            return Show::json_show(Status::mini_error, "商品不存在");
        }
        if ($goods['status']==0) {
            return Show::json_show(Status::mini_error, "商品已下架");
        }
        // 判断用户的等级是否支持该商品礼包购买
        if(in_array($goods['cate_ids'],[11,12,13,10])){
            switch ($member['commission_level']){
                case 3: //县代
                    if($goods['cate_ids'] !=10){
                        return Show::json_show(Status::mini_back, "你还不是县代，不能享受该礼包");
                    }
                    break;
                case 4:
                    if(!in_array($goods['cate_ids'],[10,11])){
                        return Show::json_show(Status::mini_back, "你还不是市代，不能享受该礼包");
                    }
                    break;
                case 5:
                    if(!in_array($goods['cate_ids'],[10,11,12])){
                        return Show::json_show(Status::mini_back, "你还不是省代，不能享受该礼包");
                    }
                    break;
                case 6:
                    if(!in_array($goods['cate_ids'],[10,11,12,13])){
                        return Show::json_show(Status::mini_back, "你还不是总代，不能享受该礼包");
                    }
                    break;
                default:
                    return Show::json_show(Status::mini_back, "你不能享受该礼包");
                    break;
            }

            $count= (new MallOrder())->where([['openid','=',$openid],['isgife','=',$goods['cate_ids']]])->count();
            if($count>0){
                return Show::json_show(Status::mini_back, "你不能重复享受该礼包");
            }

        }
        if($option_id>0){
            try {
                $skus = (new MallGoodsSku())->getGoodsSkuById($goods_id, $option_id);
            } catch (\Exception $e) {
                Log::error("goods_detail" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
                return Show::json_show(Status::mini_error, "查询失败");
            }
            if(!$skus){
                return Show::json_show(Status::mini_error, "商品规格不存在");
            }
            if($skus['stock']<$buynum || $goods['stock'] < $buynum){
                return Show::json_show(Status::mini_back, "商品库存不足");
            }
            // 用户收货地址
            try {
                $address= (new MallUserAddress())->getUserAddressByDefault($openid);
                $member =(new MallUser())->getUserByList($openid,'id,nickName,balance,commission_level');
                $goods2 = (new MallGoods())->alias('g')->field('s.id,g.title,g.cate_id,g.cate_ids,s.price,g.thumb_title,s.image,s.specs_value_ids as get_specs_value_ids')->join('mall_goods_sku s','s.goods_id=g.id')->where("s.goods_id='$goods_id' and s.id='$option_id'")->find();
            } catch (\Exception $e) {
                Log::error("address" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
                return Show::json_show(Status::mini_error, $e->getMessage());
            }
            $goodslist=array();
            if($goods2){
                $goods2['total'] =$buynum;
                $goodslist[0] =$goods2;
            }

            // 商品总额
            $goodsprice = round($goods2['price']*$buynum,2);
            $totalgoodsprice =$goodsprice;
            // 分销商等级
            try{
                $levelinfo = (new MallCommissionLevel())->getlevelInfo($member['commission_level']);
            }catch (\Exception $e) {
                Log::error("level" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
                return Show::json_show(Status::mini_error, $e->getMessage());
            }
            $zhekou =0;
            //运费
            if(in_array($goods2['cate_ids'],[10,11,12,13])){
                $persent =(new MallSetting())->getSettingInfo('shippingpersent');
                $shippingfee = round($goodsprice*$persent['option_value']/100,2);
                // 合计
                $payprice =round($shippingfee,2);
                $order=array(
                    'goodsprice'=>0.00,
                    'shippingfee'=>number_format($shippingfee,2),
                    'zhekou'=>0,
                    'levelname'=>$levelinfo['levelname'],
                    'balance'=>number_format($member['balance'],2),
                    'payprice'=>number_format($payprice,2)
                );
            }else{
                $shippingfee = 0;
                if($levelinfo){
                    $zhekou =$levelinfo['sharepersont'];
                    if($levelinfo['sharepersont'] ==0){
                        $goodsprice =round($goodsprice,2);
                    }else{
                        // 节日包和活动包（无子分类）独立商品分类不计算折扣，无佣金
                        if(in_array($goods2['cate_ids'],[8,9])){
                            $goodsprice =round($goodsprice,2);
                            $zhekou=0;
                        }else{
                            $goodsprice =round($goodsprice*$zhekou/10,2);
                        }

                    }
                }
                // 合计
                $payprice =round($goodsprice+$shippingfee,2);
                $order=array(
                    'goodsprice'=>number_format($totalgoodsprice,2),
                    'shippingfee'=>number_format($shippingfee,2),
                    'zhekou'=>$zhekou,
                    'levelname'=>$levelinfo['levelname'],
                    'balance'=>number_format($member['balance'],2),
                    'payprice'=>number_format($payprice,2)
                );
            }
            return Show::json_show(Status::mini_normal, "ok", [
                'address' =>$address ?? [],
                'goods' =>$goodslist,
                'order' =>$order,
            ]);
        }else{
            return Show::json_show(Status::mini_error, "商品规格不存在");
        }
    }

    /**
     * 立即购买下单
     * @return \think\response\Json
     * @throws \ReflectionException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function directAddToOrder(){
        $openid =$this->request->param('openid','','trim');
        $goods_id =$this->request->param('goods_id',0,'intval');
        $option_id =$this->request->param('option_id',0,'intval');
        $buynum =$this->request->param('buynum',0,'intval');
        $address_id =$this->request->param('address_id',0,'intval');
        $remark =$this->request->param('remark','','trim');
        $paytype =$this->request->param('paytype',1,'intval'); // 默认微信支付
        if($option_id>0) {
            try {
                $member =(new MallUser())->getUserByList($openid,'id,nickName,balance,commission_level,parent_id');
                $goods = (new MallGoods())->alias('g')->field('s.id,g.cate_id,g.cate_ids,g.title,s.price,g.thumb_title,s.image,s.stock,g.stock as total_stock,s.specs_value_ids as option_name')->join('mall_goods_sku s','s.goods_id=g.id')->where("s.goods_id='$goods_id' and s.id='$option_id'")->find();
                $address = (new MallUserAddress())->getUserAddressById($address_id);
            } catch (\Exception $e) {
                Log::error("goods_toorder" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
                return Show::json_show(Status::mini_error, "查询失败");
            }
            if (!$goods) {
                return Show::json_show(Status::mini_error, "商品不存在");
            }
            if(empty($address)){
                return Show::json_show(Status::mini_error, "用户收货地址不存在");
            }
            if(empty($member)){
                return Show::json_show(Status::mini_error, "用户不存在");
            }
            if ($goods['stock'] < $buynum || $goods['total_stock'] < $buynum) {
                return Show::json_show(Status::mini_error, "商品库存不足");
            }

            // 判断用户的等级是否支持该商品礼包购买
            if(in_array($goods['cate_ids'],[11,12,13,10])){
                switch ($member['commission_level']){
                    case 2: //县代
                        if($goods['cate_ids'] !=10){
                            return Show::json_show(Status::mini_error, "你还不是县代，不能享受该礼包");
                        }
                        break;
                    case 3:
                        if(!in_array($goods['cate_ids'],[10,11])){
                            return Show::json_show(Status::mini_error, "你还不是市代，不能享受该礼包");
                        }
                        break;
                    case 4:
                        if(!in_array($goods['cate_ids'],[10,11,12])){
                            return Show::json_show(Status::mini_error, "你还不是省代，不能享受该礼包");
                        }
                        break;
                    case 5:
                        if(!in_array($goods['cate_ids'],[10,11,12,13])){
                            return Show::json_show(Status::mini_error, "你还不是总代，不能享受该礼包");
                        }
                        break;
                    default:
                        return Show::json_show(Status::mini_error, "你不能享受该礼包");
                        break;
                }

                $count= (new MallOrder())->where([['openid','=',$openid],['isgife','=',$goods['cate_ids']]])->count();
                if($count>0){
                    return Show::json_show(Status::mini_error, "你不能重复享受该礼包");
                }
            }

            // 商品总额
            $totalgoodsprice=$goodsprice = round($goods['price']*$buynum,2);
            $shippingfee =0;  //运费
            // 分销商等级
            try{
                $levelinfo = (new MallCommissionLevel())->getlevelInfo($member['commission_level']);
            }catch (\Exception $e) {
                Log::error("level" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
                return Show::json_show(Status::mini_error, $e->getMessage());
            }
            $zhekou =0;
            $isyes =0;
            //运费
            if(in_array($goods['cate_ids'],[10,11,12,13])){
                $persent =(new MallSetting())->getSettingInfo('shippingpersent');
                $shippingfee = round($goodsprice*$persent['option_value']/100,2);
                // 合计
                $payprice =round($shippingfee,2);

            }else{
                if($levelinfo){
                    $zhekou =$levelinfo['sharepersont'];
                    if($levelinfo['sharepersont'] == 0){
                        $goodsprice =round($goodsprice,2);
                    }else{

                        // 节日包和活动包（无子分类）独立商品分类不计算折扣，无佣金
                        if(in_array($goods['cate_ids'],[8,9])){
                            $goodsprice =round($goodsprice,2);
                            $isyes =1;
                        }else{
                            $goodsprice =round($goodsprice*$zhekou/10,2);
                        }
                    }
                }
                // 合计
                $payprice =round($goodsprice+$shippingfee,2);
            }

            $discountprice =round($totalgoodsprice-$payprice,2);
            // 计算分销返利
            $commission =0;
            $againmoney=0;
            if($member['parent_id']>0){
                try{
                    $parentmember =(new MallUser())->getUserById($member['parent_id'],'id,nickName,balance,commission_level,parent_id');
                    if($parentmember){
                        $parentlevelinfo = (new MallCommissionLevel())->getlevelInfo($parentmember['commission_level']);
                    }
                }catch (\Exception $e) {
                    Log::error("level" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
                    return Show::json_show(Status::mini_error, $e->getMessage());
                }
                if($parentlevelinfo){
                    $count=(new MallOrder())->getOrderByCount([['orderstatus','in',[1,2,3,4]],['openid','=',$openid]]);

                    // 直推佣金
                    if($count == 0){
                        //$commission=$parentlevelinfo['commission_firstmoney'];
                        $commission =round($payprice*$parentlevelinfo['commission_firstmoney']/100,2);
                    }
                    // 复购
                    if($count>0){
                        $againmoney=round($payprice*$parentlevelinfo['commission_againpersont']/100,2);
                    }
                }
            }
            $ordermodel =(new MallOrder());
            $data =array(
                'openid' =>$openid,
                'ordersn' =>Str::RandomStr(),
                'commission' =>$commission,
                'againprice' =>$againmoney,
                'address_id' =>$address_id,
                'realname' =>$address['realname'],
                'mobile'   =>$address['mobile'],
                'address'  =>$address['cityarea'].$address['locatarea'].$address['address'],
                'isgife'  =>$goods['cate_ids'],
                'shippingfee' =>$shippingfee,
                'payprice' =>$payprice,
                'discountprice' =>$discountprice,
                'orderprice' =>$totalgoodsprice,
                'paytype'=>$paytype,
                'isyes'   =>$isyes,
                'remark' =>$remark,
                'orderstatus' =>0
            );
            $ordermodel->startTrans();
            try{
                 $ordermodel->save($data);
                 $order_id=$ordermodel->id;
                 $goodsdata =array(
                     'order_id'   =>$order_id,
                     'goods_id'   =>$goods_id,
                     'total'      =>$buynum,
                     'price'      =>$goods['price'],
                     'option_id'  =>$goods['id'],
                     'option_name'=>$goods['option_name'],
                     'image'      =>$goods['image'],
                     'goods_name' =>$goods['title']
                 );
                (new MallOrderGoods())->save($goodsdata);
                // 下单减库存
                (new MallGoodsSku())->where([['id','=',$option_id]])->dec('stock',$buynum)->update();
                (new MallGoods())->where([['id','=',$goods_id]])->dec('stock',$buynum)->update();
                (new MallGoods())->where([['id','=',$goods_id]])->Inc('sales',$buynum)->update();
                // 写入支付记录表
                $paylog =array(
                    'openid'=>$openid,
                    'ordersn'=>Str::RandomStr(),
                    'order_id'=>$order_id,
                    'type'=>1,
                    'money'=>$data['payprice'],
                    'status'=>0
                );
                (new MallUserPaylog())->save($paylog);
            }catch (\Exception $e){
                $ordermodel->rollback();
                return Show::json_show(Status::mini_error, "下单失败，请稍后重试");
            }
            // 支付参数生成、
            $objClass = ArrClass::payAttr();
            $obj = ArrClass::initClass('wx', $objClass, [], true);
            $url = (string)url('/pay/notify/index',[],true,true);
            $paydata = [
                'body' => '共享商城下单',
                'out_trade_no' => $paylog['ordersn'],
                'total_fee' => $data['payprice'] * 100,
                'spbill_create_ip' => $this->request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' => $url, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'attach' => 'payshop',
                'openid' => $openid,
            ];
            $jsondata = $obj->order($paydata);

            $wechatpayarray = [];
            if ($jsondata) {
                $wechatpay = $obj->jssdk($jsondata['prepay_id']);
                $wechatpayarray = json_decode($wechatpay, true);
            } else {
                $wechatpayarray = $jsondata;
            }
            $ordermodel->commit();
            return Show::json_show(Status::mini_normal, "ok", [
                'wechat' =>$wechatpayarray,
                'ordersn' =>$data['ordersn']
            ]);
        }else{
            return Show::json_show(Status::mini_error, "商品规格不存在");
        }
    }

    /**
     * 购物车下单
     * @return \think\response\Json
     */
    public function AddToOrder(){
        $openid =$this->request->param('openid','','trim');
        $cart_ids =$this->request->param('cart_ids','','trim');
        $address_id =$this->request->param('address_id',0,'intval');
        $remark =$this->request->param('remark','','trim');
        $paytype =$this->request->param('paytype',1,'intval'); // 默认微信支付
        if (!$cart_ids) {
            return Show::json_show(Status::mini_error, '请选择购买商品');
        }
        try{
            $goods=(new MallCart())->getCartListByIds($cart_ids);
            $address = (new MallUserAddress())->getUserAddressById($address_id);
            $member =(new MallUser())->getUserByList($openid,'id,nickName,balance,commission_level,parent_id');
        }catch (\Exception $e){
            Log::error("carttoorder" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, '查询失败');
        }

        if(empty($address)){
            return Show::json_show(Status::mini_error, "用户收货地址不存在");
        }
        if(empty($member)){
            return Show::json_show(Status::mini_error, "用户不存在");
        }
        if(empty($goods)){
            return Show::json_show(Status::mini_error, "购物车商品不存在");
        }

        $totalgoodsprice=0;
        foreach ($goods as $k=>$v){
            $goodsinfo =(new MallGoods())->alias('g')
                ->field('g.stock as total_stock,s.stock,s.goods_id')
                ->join('mall_goods_sku s','s.goods_id=g.id')
                ->where("s.goods_id='".$v['goods_id']."'")->find();

            if ($v['total'] > $goodsinfo['stock'] || $goodsinfo['total_stock'] < $v['total']) {
                return Show::json_show(Status::mini_error, "商品库存不足");
            }
            $totalgoodsprice+=round($v['price']*$v['total'],2);
        }
        $goodsprice =$totalgoodsprice;
        $shippingfee =0;  //运费
        // 分销商等级
        try{
            $levelinfo = (new MallCommissionLevel())->getlevelInfo($member['commission_level']);
        }catch (\Exception $e) {
            Log::error("level" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        $zhekou =0;
        if($levelinfo){
            $zhekou =$levelinfo['sharepersont'];
            if($zhekou >0){
                $goodsprice =round($goodsprice*$zhekou/10,2);
            }

        }
        // 合计
        $payprice =round($goodsprice+$shippingfee,2);
        $discountprice =round($totalgoodsprice-$payprice,2);
        // 计算分销返利
        $commission =0;
        $againmoney=0;
        if($member['parent_id']>0){
            try{
                $parentmember =(new MallUser())->getUserById($member['parent_id'],'id,nickName,balance,commission_level,parent_id');
                if($parentmember){
                    $parentlevelinfo = (new MallCommissionLevel())->getlevelInfo($parentmember['commission_level']);
                }
            }catch (\Exception $e) {
                Log::error("level" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
                return Show::json_show(Status::mini_error, $e->getMessage());
            }
            if($parentlevelinfo){
                $count=(new MallOrder())->getOrderByCount([['orderstatus','in',[1,2,3,4]],['openid','=',$openid]]);
                // 直推佣金
                if($count ==0){
                    //$commission=$parentlevelinfo['commission_firstmoney'];
                    $commission =round($payprice*$parentlevelinfo['commission_firstmoney']/100,2);
                }
                // 复购
                if($count>0){
                    $againmoney=round($payprice*$parentlevelinfo['commission_againpersont']/100,2);
                }
            }
        }
        $ordermodel =(new MallOrder());
        $data =array(
            'openid' =>$openid,
            'ordersn' =>Str::RandomStr(),
            'commission' =>$commission,
            'againprice'   =>$againmoney,
            'address_id' =>$address_id,
            'realname' =>$address['realname'],
            'mobile'   =>$address['mobile'],
            'address'  =>$address['cityarea'].$address['locatarea'].$address['address'],
            'shippingfee' =>$shippingfee,
            'payprice' =>$payprice,
            'remark' =>$remark,
            'discountprice' =>$discountprice,
            'orderprice' =>$totalgoodsprice,
            'paytype'=>$paytype,
            'orderstatus' =>0
        );
        $ordermodel->startTrans();
        try{
            $ordermodel->save($data);
            $order_id=$ordermodel->id;
            foreach ($goods as $kk=>$vv){
                $goodsdata =array(
                    'order_id'   =>$order_id,
                    'goods_id'   =>$vv['goods_id'],
                    'total'      =>$vv['total'],
                    'price'      =>$vv['price'],
                    'option_id'  =>$vv['option_id'],
                    'option_name'=>$vv['option_name'],
                    'image'      =>$vv['image'],
                    'goods_name' =>$vv['title']
                );
                (new MallOrderGoods())->save($goodsdata);
            }
            (new MallCart())->deleteByCartId($cart_ids);
            foreach ($goods as $kkk=>$vvv){
                // 下单减库存
                (new MallGoodsSku())->where([['id','=',$vvv['option_id']]])->dec('stock',$vvv['total'])->update();
                (new MallGoods())->where([['id','=',$vvv['goods_id']]])->dec('stock',$vvv['total'])->update();
                (new MallGoods())->where([['id','=',$vvv['goods_id']]])->Inc('sales',$vvv['total'])->update();
            }
            // 写入支付记录表
            $paylog =array(
                'openid'=>$openid,
                'ordersn'=>Str::RandomStr(),
                'order_id'=>$order_id,
                'type'=>1,
                'money'=>$data['payprice'],
                'status'=>0
                );
            (new MallUserPaylog())->save($paylog);
            // 支付参数生成
            $objClass = ArrClass::payAttr();
            $obj = ArrClass::initClass('wx', $objClass, [], true);
            $url = (string)url('/pay/notify/index',[],true,true);
            $paydata = [
                'body' => '共享商城下单',
                'out_trade_no' => $paylog['ordersn'],
                'total_fee' => $paylog['money'] * 100,
                'spbill_create_ip' => $this->request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' => $url, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'attach' => 'payshop',
                'openid' => $openid,
            ];
            $jsondata = $obj->order($paydata);
            $wechatpayarray = [];
            if ($jsondata) {
                $wechatpay = $obj->jssdk($jsondata['prepay_id']);
                $wechatpayarray = json_decode($wechatpay, true);
            } else {
                $wechatpayarray = $jsondata;
            }
        }catch (\Exception $e){
            $ordermodel->rollback();
            return Show::json_show(Status::mini_error, $e->getMessage());
        }

        $ordermodel->commit();
        return Show::json_show(Status::mini_normal, "ok", [
            'wechat' =>$wechatpayarray,
            'ordersn' =>$data['ordersn']
        ]);
    }

    /**
     * 重复支付订单接口
     * @return \think\response\Json|void
     * @throws \think\Exception
     */
    public function orderToPay()
    {
        $openid = $this->request->param('openid', '', 'trim');
        $ordersn = $this->request->param('ordersn', '', 'trim');
        try {
            $orderinfo = (new MallOrder())->getOrderById([['openid','=',$openid],['ordersn','=',$ordersn]]);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '查询失败');
        }
        if (!$orderinfo) {
            return Show::json_show(Status::mini_normal, '订单不存在');
        }
        $ordersn = Str::RandomStr();
        try {
            $paylog = (new MallUserPaylog())->getUserPaylogByOpenid($openid,$orderinfo['id']);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '查询失败');
        }
        if (!$paylog) {
            return Show::json_show(Status::mini_normal, '订单异常');
        }
        $paylog->save(array('ordersn' => $ordersn, 'money' => $orderinfo['payprice']));

        $objClass = ArrClass::payAttr();
        $obj = ArrClass::initClass('wx', $objClass, [], true);
        $url = (string)url('/pay/notify/index',[],true,true);
        $data = [
            'body' => '共享商城下单',
            'out_trade_no' => $ordersn,
            'total_fee' => $orderinfo['payprice'] * 100,
            'spbill_create_ip' => $this->request->ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => $url, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'attach' => 'payshop',
            'openid' => $openid,
        ];
        $jsondata = $obj->order($data);
        $wechatpay = $obj->jssdk($jsondata['prepay_id']);
        return Show::json_show(Status::mini_normal, "ok", [
            'ordersn' => $ordersn,
            'wechat' => json_decode($wechatpay, true)
        ]);
    }


    /**
     *  删除订单
     * @return \think\response\Json
     */
    public function deleteOrder()
    {
        $order_id = $this->request->param('order_id', '', 'trim');
        $openid = $this->request->param('openid', '', 'trim');

        try {
            $orderinfo = (new MallOrder())->getOrderById([['openid','=',$openid],['id','=',$order_id]]);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '查询失败');
        }
        if (!$orderinfo) {
            return Show::json_show(Status::mini_normal, '订单不存在');
        }
        try {
            $orderinfo->save(array('deleted' => '1'));
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '更新失败');
        }
        return Show::json_show(Status::mini_normal, "删除成功", []);
    }

    /**
     * 处理取消订单
     * @return \think\response\Json|void
     */
    public function doCancelsOrder()
    {
        $openid = $this->request->param('openid', '', 'trim');
        $order_id = $this->request->param('order_id', '', 'intval');
        try {
            $orderinfo = (new MallOrder())->getOrderById([['openid','=',$openid],['id','=',$order_id]]);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, '查询失败');
        }
        if (!$orderinfo) {
            return Show::json_show(Status::mini_error, '订单不存在');
        }
        if($orderinfo['orderstatus'] == 0){
            $orderinfo->save(array('orderstatus' => 9, 'canceltime' => time()));
        }else {
            return Show::json_show(Status::mini_error, '操作失败');
        }
        return Show::json_show(Status::mini_normal, "操作成功", []);
    }

    /**
     * 确认收货
     * @return \think\response\Json
     */
    public function confirmOrder(){
        $order_id =$this->request->param('order_id','','intval');
        $openid =$this->request->param('openid','','trim');
        $ordermodel=(new MallOrder());
        try{
           $order= $ordermodel->getOrderById([['id','=',$order_id],['openid','=',$openid]]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error, '查询失败');
        }

        if(empty($order)){
            return Show::json_show(Status::mini_error, '订单不存在');
        }
        if($order['orderstatus'] !=2){
            return Show::json_show(Status::mini_error, '您不能进行改操作');
        }
        $ordermodel->startTrans();
        try{
            $order->save(array('orderstatus'=>3,'confirm_time'=>time()));
            if($order['isyes'] == 0){
                // 付款完成，返利以及分销商升级
                $member = (new MallUser())->getUserByList($order['openid'],'id,openid,nickName,commission_level,parent_id');
                $levels =(new MallCommissionLevel())->getLevels();
                foreach ($levels as $k=>$v){
                    // 满足购买商品金额进行升级
                    if($v['ordermoney'] == $order['payprice'] && $v['id']>$member['commission_level']){
                        (new MallUser())->where("id",$member['id'])->save(array('commission_level'=>$v['id'],'level_time'=>time()));
                    }
                }
                if($member['parent_id'] >0){
                    $parentmember = (new MallUser())->getUserById($member['parent_id'],'id,openid,nickName,commission_level');
                    $levelinfo =(new MallCommissionLevel())->getlevelInfo($parentmember['commission_level']);
                    // 复购返利
                    $count=$ordermodel->getOrderByCount([['orderstatus','in',[3,4]],['openid','=',$member['openid']]]);
                    if($count==1){
                        if($order['commission']>0){
                            (new MallAccountLog())->saveAccoutLog($order_id,$parentmember['openid'],$order['commission'],3,'推荐返利');
                        }
                    }
                    if($order['againprice']>0){
                        (new MallAccountLog())->saveAccoutLog($order_id,$parentmember['openid'],$order['againprice'],4,'复购返利');

                        // 存在复购奖励，计算团队奖励给推荐人。
                        $set=(new MallSetting())->getSettingInfo('teamset');
                        $teamlprice =round($order['againprice']*$set['option_value']/100,2);
                        if($teamlprice>0){
                            (new MallAccountLog())->saveAccoutLog($order_id,$parentmember['openid'],$teamlprice,5,'团队奖励');
                        }
                    }
                    $order->save(array('isget'=>1)); // 首单返佣入账
                    // 下级会员数满足条件 升级等级
                    $memcount =(new MallUser())->getMemCount($member['parent_id']);
                    if($levelinfo['membercount']<=$memcount && $levelinfo['membercount']>0 && $parentmember['commission_level']<6){
                        (new MallUser())->where("id",$member['parent_id'])->inc('commission_level',1)->update();
                        (new MallUser())->where("id",$member['parent_id'])->save(array('level_time'=>time()));
                    }
                }
            }

        }catch (\Exception $e){
            $ordermodel->rollback();
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        $ordermodel->commit();
        return Show::json_show(Status::mini_normal, "确认收货成功", [

        ]);
    }

    /**
     * 商城订单申请售后
     * @return \think\response\Json
     */
    public  function orderToRefund(){
        $openid =$this->request->param('openid','','trim');
        $order_id =$this->request->param('order_id','','trim');
        $type =$this->request->param('type','','trim');
        $reason =$this->request->param('reason','','trim');
        $remark =$this->request->param('remark','','trim');
        $mobile =$this->request->param('mobile','','trim');
        $imgs =$this->request->param('imgs','','trim');

        if(!$reason || !$type || !$remark){
            return Show::json_show(Status::mini_error,'退款必要信息请填写完整');
        }
        if (!preg_match('/^(?:(?:\+|00)86)?1[3-9]\d{9}$/', $mobile)) {
            return Show::json_show(Status::mini_error, '联系电话输入有误');
        }
        try{
            $orderinfo =(new MallOrder())->getOrderById([['openid','=',$openid],['id','=',$order_id]]);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(!$orderinfo || ($orderinfo &&  !in_array($orderinfo['orderstatus'],[1,2,3,4]))){
            return Show::json_show(Status::mini_error,'订单不存在或不能申请售后');
        }
        $data =array(
            'openid' =>$openid,
            'order_id'=>$order_id,
            'refund_type' =>$type,
            'refund_reason'=>$reason,
            'remark'    =>$remark,
            'mobile'=>$mobile,
            'refund_money' =>$orderinfo['payprice']
        );
        if($imgs && is_array($imgs)){
            $data['refund_imgs'] =json_encode($imgs);
        }

        try{
            $result=(new MallOrderRefund())->save($data);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,'申请失败');
        }
        if($result){
            $orderdata=array('isapplyrefund'=>1,'orderstatus'=>4);
            (new MallOrder())->where("id",$order_id)->save($orderdata);
        }
        return Show::json_show(Status::mysql_normal,'操作成功',[
        ]);
    }
}